package br.com.fixtrader.quoteserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import algotrader.book.Book;

public class ClientTask implements Runnable{

	private Socket s;
	private BufferedReader in;
	private PrintWriter out;
	private QuoteServer quoteServer;
	
	public ClientTask(Socket s,QuoteServer quoteServer) {
		System.out.println("Criando nova ClientTask");
		this.s = s;
		this.quoteServer = quoteServer;
		try {
			this.in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			this.out = new PrintWriter(s.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		String line = null;
		while(true) {
			try {
				if ((line = in.readLine()) == null)
					continue;
				    processaPedido(line);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void processaPedido(String line) throws IOException {
		String values[] = line.split(" ");
		System.out.println(values[0]);
		if (values[0].equals("bqt")) {
			
			Book book = null;
			if((book = quoteServer.getBook(values[1])) == null) {
				quoteServer.requestBook(values[1],s.getOutputStream());
			} else {
				// o book jah estah no bookmanager, eh preciso decidir se o envio como Java object ou como mensagens...
				out.print(book); // assim eh enviado o objeto inteiro
			}
			
		} else if (values[0].equals("ubq")) {
			quoteServer.unsubscribe(values[1],s.getOutputStream());
		}
	}
}
